import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import util from '../util'
import {request} from '../util/request.js'
import {Message} from 'element-ui'

/**
 *  避免重复路由，引发的错误报警
 */
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
	return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const routes = [
	{
		path: '/',
		name: 'Index',
		component: () => import( /* webpackChunkName: "home" */ '../views/Home.vue')
	},
	{
		path: '/home', /* 首页 */
		name: 'Home',
		component: () => import( /* webpackChunkName: "home" */ '../views/Home.vue')
	},
	{
		path: '/appStore',  /* 应用商店 */
		name: 'appStore',
		component: () => import( /* webpackChunkName: "appStore" */ '../views/AppStore.vue')
	},
	{
		path: '/devCommunity', /* 开发者社区 */
		name: 'devCommunity',
		component: () => import( /* webpackChunkName: "devCommunity" */ '../views/development/Community.vue')
	},
	{
		path: '/devWorkOrderManagement', /* 开发者认证工单管理 */
		name: 'devWorkOrderManagement',
		component: () => import( /* webpackChunkName: "devWorkOrderManagement" */ '../views/development/WorkOrderManagement.vue')
	},
	{
		path: '/devCertInfoManagement', /* 开发者认证资料模板管理 */
		name: 'devCertInfoManagement',
		component: () => import( /* webpackChunkName: "devCertInfoManagement" */ '../views/development/CertInfoManagement.vue')
	},
	{
		path: '/devCertApply', /* 开发者认证申请 */
		name: 'devCertApply',
		component: () => import( /* webpackChunkName: "devCertApply" */ '../views/development/CertApply.vue')
	},
	{
		path: '/devWorkOrderDetail', /* 开发者认证申请工单详情 */
		name: 'devWorkOrderDetail',
		component: () => import( /* webpackChunkName: "devWorkOrderDetail" */ '../views/development/WorkOrderDetail.vue')
	},
	{
		path: '/workorderManagement', /* 工单管理 */
		name: 'workorderManagement',
		component: () => import( /* webpackChunkName: "workorderManagement" */ '../views/workorderManagement/List.vue')
	},
	{
		path: '/tenantManagement', /* 多租户管理 */
		name: 'tenantManagement',
		component: () => import( /* webpackChunkName: "tenantManagement" */ '../views/tenantManagement/List.vue')
	},
	{
		path: '/myResources', /* 我的资源 */
		name: 'myResources',
		component: () => import( /* webpackChunkName: "myResources" */ '../views/myResources/List.vue')
	},
	{
		path: '/resApplyWorkOrderManagement', /* 资源申请工单管理 */
		name: 'resApplyWorkOrderManagement',
		component: () => import( /* webpackChunkName: "resApplyWorkOrderManagement" */ '../views/resourceApply/List.vue')
	},
	{
		path: '/paasApply', /* PaaS资源申请 */
		name: 'paasApply',
		component: () => import( /* webpackChunkName: "paasApply" */ '../views/resourceApply/PaaSApply.vue')
	},
	{
		path: '/iaasApply',  /* IaaS资源申请 */
		name: 'iaasApply',
		component: () => import( /* webpackChunkName: "iaasApply" */ '../views/resourceApply/IaaSApply.vue')
	},
	{
		path: '/resourcesManagement',  /* IaaS资源管理 */
		name: 'resourcesManagement',
		component: () => import( /* webpackChunkName: "resourcesManagement" */
			'../views/resourcesManagement/List.vue')
	},
	{
		path: '/docManagement',  /* 文档管理 */
		name: 'docManagement',
		component: () => import( /* webpackChunkName: "docManagement" */ '../views/docManagement/List.vue')
	},
	{
		path: '/helpCenter', /* 帮助中心 */
		name: 'helpCenter',
		component: () => import( /* webpackChunkName: "helpCenter" */ '../views/helpCenter/helpCenter.vue')
	},
	{
		path: '/accountApproval', /* 账号审批 */
		name: 'accountApproval',
		component: () => import( /* webpackChunkName: "accountApproval" */ '../views/systemManagement/accountApproval/List.vue')
	},
	{
		path: '/homePageManagement', /* 首页配置管理 */
		name: 'homePageManagement',
		component: () => import( /* webpackChunkName: "homePageManagement" */ '../views/homePageManagement/List.vue')
	},
	{
		path: '/helpCenterManagement', /* 帮助中心配置管理 */
		name: 'helpCenterManagement',
		component: () => import( /* webpackChunkName: "helpCenterManagement" */ '../views/helpCenterManagement/List.vue')
	},
	{
		path: '/userManagement', /* 租户组织机构（用户）管理 */
		name: 'userManagement',
		component: () => import( /* webpackChunkName: "userManagement" */ '../views/userManagement/List.vue')
	},
	{
		path: '/roleManagement', /* 租户角色权限管理 */
		name: 'roleManagement',
		component: () => import( /* webpackChunkName: "roleManagement" */ '../views/roleManagement/List.vue'),
	},
	{
		path: '/systemCertification', /* 系统认证 */
		name: 'systemCertification',
		component: () => import( /* webpackChunkName: "systemCertification" */ '../views/systemManagement/systemCertification/List.vue')
	},
	{
		path: '/logManagement', /* 日志管理 */
		name: 'logManagement',
		component: () => import( /* webpackChunkName: "logManagement" */ '../views/systemManagement/logManagement/List.vue')
	},
	{
		path: '/sysUserManagement', /* 系统组织机构（用户）管理 */
		name: 'sysUserManagement',
		component: () => import( /* webpackChunkName: "sysUserManagement" */ '../views/systemManagement/userManagement/List.vue')
	},
	{
		path: '/sysRoleManagement', /* 系统角色权限管理 */
		name: 'sysRoleManagement',
		component: () => import( /* webpackChunkName: "sysRoleManagement" */ '../views/systemManagement/roleManagement/List.vue')
	},
	{
		path: '/register', /* 注册 */
		name: 'register',
		component: () => import( /* webpackChunkName: "register" */ '../views/login/Register.vue')
	}
]

const router = new VueRouter({
	mode: 'history',
	base: process.env.BASE_URL,
	routes
})


//在进入路由之前， 每一次都会执行此方法  全局钩子
router.beforeEach(function(to, from, next) {
	let query = util.parseUrl(location.href).query;
	
	if(to.path == '/register') {
		// 如果是注册和首页，则next
		next();
	} else if(to.path == '/') {
		if(query && query.visitor==1) { //如果是游客模式，直接进入首页
			next();
		} else { //非游客模式，转到SSO验证是否登录
			location.href = `${API.SSO_URL}?response_type=code&client_id=EIP&redirect_uri=${API.EIIP_URL}?visitor=1`
		}
	} else if(to.path == '/home' ){ 
		// 判断URL是否有code
		if(query && query.code) { //如果有则完成登录
			// 截取code，并请求门户接口换取token和loginUser
			request({
				url : `/api/ssoLogin?code=${query.code}`,
			}).then( res=> {
				if(res.data.code == 200) {
					// 保存至session以及store
					sessionStorage.setItem("eiip-token", res.data['eiip-token']);  //门户用
					sessionStorage.setItem("sso-token", res.data['sso-token']); //SSO用(SSO目前实现有问题，后期这个token会去掉)
					sessionStorage.setItem("loginUser", JSON.stringify(res.data.userInfo))
					sessionStorage.setItem("menus", JSON.stringify(res.data.userInfo.menus))
					sessionStorage.setItem('uid', res.data.uid);
					store.dispatch('setLoginUser', res.data.userInfo) //保持用户到store中
					document.cookie = `eiip-token=${res.data['eiip-token']};`
					// next下一步
					console.log('登录成功，即将跳转 / ');
					//请求Paas平台获取paasToken
					request({
						url: `${API.PAAS_API}?accessToken=${res.data['sso-token']}&id=${res.data.uid}`
					}).then( res => {
						//保存paasToken
						sessionStorage.setItem('paas-token', res.data.data);
						location.href = `${API.EIIP_URL}` //最终跳转首页
					}).catch( err => {
						Message.error('paas平台获取令牌失败')
						location.href = `${API.EIIP_URL}` //最终跳转首页
					})
				}
			})
		} else { //否则，进入首页
			next();
		}
	} else { //其它路由需要权限校验
		if(sessionStorage.getItem('eiip-token')) {
			// 如果有token, next下一步
			next();
		} else { 
			// 否则跳转至SSO登录页
			location.href = `${API.SSO_URL}?response_type=code&client_id=EIP&redirect_uri=${API.EIIP_URL}`
		}
	}
});

// router.afterEach(function(to) {})

export default router
